package com.weng.db.demo;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DbUtil {

    /**
     * 获取当前数据源表结构
     * @param  schemaPattern 达梦：SYSDBA  人大金仓：public
     * @return
     */
    public static List<String> getTableNames(String jdbcUrl, String schemaPattern, DatabaseMetaData metaData)
            throws SQLException {
        String dbName = DbUtil.getSchemaByJdbcUrl(jdbcUrl);
        List<String> tableList = new ArrayList<String>();
        ResultSet tables = metaData.getTables(dbName, schemaPattern, "%", new String[]{"TABLE", "VIEW"});
        if (null != tables) {
            while (tables.next()) {
                String tableName = tables.getString("table_name");
                if(tableName != null && tableName.indexOf("##") == 0){
                   // 处理达梦的特殊情况
                    continue;
                }
                tableList.add(tableName);
            }
            tables.close();
        }
        return tableList;
    }

    /**
     * 通过jdbc获取schema库名，
     * 如通过：  url: jdbc:mysql://127.0.0.1:3306/warehouse?allowMultiQueries=true
     *  获取名称：warehouse
     * @param jdbcUrl
     * @return
     */
    public static String getSchemaByJdbcUrl(String jdbcUrl){

        String schema = "";
        if(jdbcUrl != null){
            if(jdbcUrl.indexOf("?") > 0){
                jdbcUrl = jdbcUrl.substring(0, jdbcUrl.indexOf("?"));
            }
            schema = jdbcUrl.substring(jdbcUrl.lastIndexOf("/") + 1, jdbcUrl.length());
            return schema;
        }else{
        }
        return schema;
    }
}